package com.vogue.supplymall.admin.business.common;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * The type Qr code utils.
 * 二维码工具
 *
 * @author zhangliang
 * Create in 2018-07-13
 */
@Component("qrCodeUtils")
public class QRCodeUtils implements Serializable {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_QRCODEUTILS = LoggerFactory.getLogger(QRCodeUtils.class);

    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
    private static final int WIDTH = 200; // 二维码宽
    private static final int HEIGHT = 200; // 二维码高
    private static final int HEIGHT_WITH_TEXT = 225; // 二维码高-包含文字
    private static final int TEXT_SIZE = 20; // 文字高
    private static final int TEXT_X = 100; // 写文字X坐标

    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8"); // 设置编码方式
            put(EncodeHintType.MARGIN, 1);
        }
    };


    /**
     * 生成带logo的二维码图片
     *
     * @param logoFile the logo file
     * @param qrUrl    the qr url
     * @return the buffered image
     */
    @SuppressWarnings("all")
    public InputStream drawLogoQRCode(File logoFile, String qrUrl) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(qrUrl)) {
            return null;
        }
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix matrix = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, matrix.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            // 绘制logo
            if (null != logoFile) {
                if (logoFile.exists()) {
                    // 构建绘图对象
                    Graphics2D graphics = image.createGraphics();
                    // 读取Logo图片
                    BufferedImage logo = ImageIO.read(logoFile);
                    int x = WIDTH * 2 / 5;
                    int y = HEIGHT * 2 / 5;
                    int widthLogo = WIDTH * 2 / 10;
                    int heightLogo = HEIGHT * 2 / 10;
                    // 开始绘制logo图片
                    graphics.drawImage(logo, x, y, widthLogo, heightLogo, null);
                    // 绘制logo的边框（目前达不到微信的效果，暂时不使用了）
//                graphics.setStroke(new BasicStroke(2));
//                graphics.setColor(Color.WHITE);
//                graphics.drawRect(x, y, widthLogo, heightLogo);
                    graphics.dispose();
                    logo.flush();
                }
            }

            image.flush();
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(image, "png", imOut);
            InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
            return inputStream;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LOGGER_QRCODEUTILS.info("生成二维码 >> 未找到文件");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER_QRCODEUTILS.info("生成二维码 >> 文件读写失败");
        } catch (WriterException e) {
            e.printStackTrace();
            LOGGER_QRCODEUTILS.info("生成二维码 >> 生成二维码失败");
        }
        return null;
    }
}
